import { PostService } from '~/server/database/services/postService'
import LikeService from '~/server/database/services/likeService'

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event)
    const page = parseInt(query.page as string) || 1
    const pageSize = parseInt(query.pageSize as string) || 10
    const search = query.search as string

    const result = await PostService.getPosts(page, pageSize, search)

    // 如果用户已登录，检查点赞状态
    let userId: number | null = null
    try {
      const { requireAuth } = await import('~/server/utils/auth')
      const user = await requireAuth(event)
      userId = user.id
    } catch {
      // 用户未登录，跳过点赞状态检查
    }

    // 为每个帖子添加点赞状态
    if (userId) {
      for (const post of result.posts) {
        post.isLiked = await LikeService.isLiked(userId, 'post', post.id)
      }
    }

    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal Server Error',
      data: { message: '获取帖子列表失败' }
    })
  }
})
